<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">系统登录</h2>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item prop="remember">
          <el-checkbox v-model="formData.remember">记住我</el-checkbox>
        </el-form-item>

        <el-button
          type="primary"
          :loading="loading"
          @click="handleLogin"
          class="login-btn"
        >
          登录
        </el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

import {LoginApi} from '../../api/index.js'
const router = useRouter()

// 1. 表单数据初始化（关键修正点）
const formData = reactive({
  username: '',
  password: '',
  remember: false
})

// 2. 表单引用（使用ref）
const formRef = ref(null)
const loading = ref(false)

// 3. 验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到12个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在6到16个字符', trigger: 'blur' }
  ]
})

// 4. 登录方法
const handleLogin = async () => {
  // 确保formRef已绑定
  if (!formRef.value) return

  try {
    // 表单验证
    await formRef.value.validate()

    loading.value = true
    const res = await LoginApi( {
      username: formData.username,
      password: formData.password
    })

    if (res.data.code === 200) {
      ElMessage.success('登录成功')
      localStorage.setItem('token', res.data.token)
      router.push('/')
    } else {
      ElMessage.error(res.data.message || '登录失败')
    }
  } catch (error) {
    // 区分验证错误和请求错误
    if (error?.errors) {
      ElMessage.warning('请正确填写表单')
    } else {
      ElMessage.error('请求出错：' + error.message)
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 原有样式不变 */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.login-card {
  width: 400px;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.login-btn {
  width: 100%;
  margin-top: 10px;
}
</style>
